<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Repositories\UserRepositoryEloquent;
use App\User;
use App\Models\UserRelationship;
use Breadcrumbs, Toastr,Config,Validator,DB,Carbon;
use Illuminate\Http\Request;
use App\Models\FinancialDetails;

use EasyWeChat\Payment\Order;

class MemberController extends Controller{

    protected $user;

    public function __construct(UserRepositoryEloquent $user)
    {
        //parent::__construct();
        $this->user = $user;


    }

    public function userinfo(Request $request){
        $user = $request->user();
        //dd($user);
        return view('home.user.index',compact('user'));

    }

    public function recharge(Request $request){
        $user = $request->user();
        //dd($user);
        return view('home.payment.recharge',compact('user'));
    }

    public function weiXinPay(Request $request){

        $userwxinfo = session('wechat.oauth_user'); // 拿到授权用户资料
        //dd($userwxinfo);
        $wechat = app('wechat');
        $payment = $wechat->payment;
        //dd($payment);
        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'openid'           => $userwxinfo->id,
            'body'             => 'iPad mini 16G 白色',
            'detail'           => 'iPad mini 16G 白色',
            'out_trade_no'     => '1217752501201407033233368018',
            'total_fee'        => 100,
            'notify_url'       => 'http://xxx.com/order-notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            // ...
        ];
        $order = new Order($attributes);
        $result = $payment->prepare($order);
        //var_dump($order->total_fee);
        //var_dump($result);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $config = $payment->configForJSSDKPayment($prepayId);
            //echo $prepayId;
            return view('home.payment.comfirmrecharge',compact('result','order','config'));
        }else{
            echo $result->return_msg;
        }


    }

    public function saoMaPay(Request $request){

        $user = $request->user();
        
        include ('phpqrcode.php');
        require_once('merchant.php');

        $data = array();
        $money = 0.01;
        $data['user_id'] = $user->id;
        $data['money'] = $money;
        $data['fee'] = $money*0.009;
        $data['status'] = 0;
        $data['type'] = 2;
        $data['created_at'] = \Carbon\Carbon::now()->toDateTimeString();
        //$data['bank_id'] = 0;
        //商户单号
        $merchant_code = "2020600810";
        $out_trade_no = $user->id.date("YmdHis").mt_rand(1000,9999);
        $data['out_trade_no'] = $out_trade_no;
        //$res = M('FuturesRecharge')->add($data);
        $id = DB::table('recharges')->insertGetId($data);
        if(!$id){
            echo 'Error';exit;
        }
        $priKey= openssl_get_privatekey($priKey);
        //echo "Key:".$priKey,'<hr>';
        //if($data['openid']!='on8j1v9bJGetq2GiZxCSoWW5BJGY'){
            //$this->error('系统更新中');
            //echo "Key:".$priKey,'<hr>';
        //}
        $service_type = "wxpay";
        //$notify_url = "http://www.dinpay.com/Notify_Url.jsp";
        $notify_url = "http://qtest.fivip.com/futures.php/Pay/zfnotify";  
        //$notify_url = url('/zfnotify'); 
        echo $notify_url;       
        $interface_version ="V3.0"; 
        $sign_type = "RSA-S";
        //$order_no = "10002016665";
        $order_no = $out_trade_no;
        //$this->assign('order_no',$order_no);
        //$this->assign('money',$money);
        //session($order_no,0); 
        //$order_time = "2015-11-11 12:12:12";
        $order_time = date('Y-m-d H:i:s');  
        //$order_amount ="0.01" ;   
        $order_amount = $money;
        $product_name = "充值";   
        $product_code = ""; 
        $product_num = "";
        $product_desc = ""; 
        $extra_return_param = "";   
        $extend_param = "";
        $signStr = "";
        if($extend_param != ""){
            $signStr = $signStr."extend_param=".$extend_param."&";
        }
        if($extra_return_param != ""){
            $signStr = $signStr."extra_return_param=".$extra_return_param."&";
        }   
        $signStr = $signStr."interface_version=".$interface_version."&";        
        $signStr = $signStr."merchant_code=".$merchant_code."&";        
        $signStr = $signStr."notify_url=".$notify_url."&";          
        $signStr = $signStr."order_amount=".$order_amount."&";          
        $signStr = $signStr."order_no=".$order_no."&";          
        $signStr = $signStr."order_time=".$order_time."&";  
        if($product_code != ""){
            $signStr = $signStr."product_code=".$product_code."&";
        }       
        if($product_desc != ""){
            $signStr = $signStr."product_desc=".$product_desc."&";
        }
        $signStr = $signStr."product_name=".$product_name."&";

        if($product_num != ""){
            $signStr = $signStr."product_num=".$product_num."&";
        }   
        $signStr = $signStr."service_type=".$service_type;  
        openssl_sign($signStr,$sign_info,$priKey,OPENSSL_ALGO_MD5);
        $sign = urlencode(base64_encode($sign_info));           
        $postdata = "";
        if($extend_param != ""){
            $postdata = $postdata.'extend_param='.$extend_param."&";
        }
        if($extra_return_param != ""){
            $postdata = $postdata.'extra_return_param='.$extra_return_param."&";
        }
        if($product_code != ""){
            $postdata = $postdata.'product_code='.$product_code."&";
        }   
        if($product_desc != ""){
            $postdata = $postdata.'product_desc='.$product_desc."&";
        }   
        if($product_num != ""){
            $postdata = $postdata.'product_num='.$product_num."&";
        }   
        $postdata = $postdata.'merchant_code='.$merchant_code."&";
        $postdata = $postdata.'service_type='.$service_type."&";
        $postdata = $postdata.'notify_url='.$notify_url."&";
        $postdata = $postdata.'interface_version='.$interface_version."&";
        $postdata = $postdata. 'sign_type='.$sign_type."&";
        $postdata = $postdata.'sign='.$sign."&";
        $postdata = $postdata.'order_no='.$order_no."&";
        $postdata = $postdata.'order_time='.$order_time."&";
        $postdata = $postdata.'order_amount='.$order_amount."&";
        $postdata = $postdata.'product_name='.$product_name;
        //echo "发送到智付的数据为："."<br>".$postdata."<br>";
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"https://api.dinpay.com/gateway/api/weixin");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response=curl_exec($ch);
        $res=simplexml_load_string($response);
        //if($data['openid']!='on8j1v9bJGetq2GiZxCSoWW5BJGY'){
            //$this->error('系统更新中');
            //var_dump($res);
        //}
        //var_dump($res);
        $resp_code=$res->response->resp_code;           
        if($resp_code=="SUCCESS"){
            $qrcode=$res->response->trade->qrcode;
            //var_dump($qrcode);
            $pic1="./zfpay/{$out_trade_no}-qrcode.png";
            $pic2="./zfpay/{$out_trade_no}-output.png";
            $errorCorrectionLevel = 'L';
            $matrixPointSize = 10;
            if(file_exists($pic1) or file_exists($pic2)){                               
                unlink($pic1);
                unlink($pic2);
            }
            \QRcode::png ( $qrcode, $pic1, $errorCorrectionLevel, $matrixPointSize, 2 );
            $QR = $pic1;
            $logo = './logo.png';
            if ($logo !== FALSE) {
                $QR = imagecreatefromstring ( file_get_contents ( $QR ) );
                $logo = imagecreatefromstring ( file_get_contents ( $logo ) );
                $QR_width = imagesx ( $QR );
                $QR_height = imagesy ( $QR );
                $logo_width = imagesx ( $logo );
                $logo_height = imagesy ( $logo );
                $logo_qr_width = $QR_width / 7;
                $scale = $logo_width / $logo_qr_width;
                $logo_qr_height = $logo_height / $scale;
                $from_width = ($QR_width - $logo_qr_width) / 2;
                imagecopyresampled ( $QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height );
            }
            imagepng ( $QR, $pic2 );
            imagedestroy($QR);
            //$this->assign('qr',$pic2);
            //$this->display('pay');
            return view('home.payment.saoma',compact('pic2','order_no','money'));
            //echo "扫描二维码支付：" ."<br>"."<img src='{$pic2}'>";
        }
        curl_close($ch);
        
    }


    public function yinLianPay(){
        $money = 0.01;
       
        
        require_once('merchant.php');
       
        $data = array();
       
        
        $data['money'] = $money;
        $data['create_time'] = time();
        $data['is_pay'] = 0;
        $data['pay_type'] = 1;
        $data['bank_id'] = 0;
        //商户单号
        $out_trade_no = date("YmdHis").mt_rand(1000,9999);
        $data['out_trade_no'] = $out_trade_no;
        // $res = M('FuturesRecharge')->add($data);
        // if(!$res){
        //     $this->error('充值出错！');
        // }
        

        /////////////////////////////////获取商家私钥//////////////////////////////////////
        ////////////////////////get the private key of merchant///////////////////////////
    
    require_once('merchant.php');
    $priKey= openssl_get_privatekey($priKey);
    /////////////////////////////////初始化提交参数//////////////////////////////////////
    ////////////////////////initial the parameter datas/////////////////////////////////
    $merchant_code = "2020600810";
    $service_type ="direct_pay";    
    $interface_version ="V3.0";
    $pay_type = "";
    $sign_type ="RSA-S";
    $input_charset = "UTF-8";
    $notify_url ="http://www.dinpay.com";
    //$notify_url = U('Pay/ylzfnotify');      
    $order_no = $out_trade_no;  
    $order_time = date('Y-m-d H:i:s');  
    $order_amount = $money; 
    $product_name ="账号充值";  
    $product_code = ""; 
    $product_desc = ""; 
    $product_num = "";
    $show_url = ""; 
    $client_ip ="" ;    
    $bank_code = "";    
    $redo_flag = "";    
    $extend_param = "";
    $extra_return_param = "";   
    $return_url ="";        
    
    /////////////////////////////   数据签名  /////////////////////////////////
    ////////////////////////////  Data signature  ////////////////////////////

    /**
    签名规则定义如下：
    （1）参数列表中，除去sign_type、sign两个参数外，其它所有非空的参数都要参与签名，值为空的参数不用参与签名；
    （2）签名顺序按照参数名a到z的顺序排序，若遇到相同首字母，则看第二个字母，以此类推，同时将商家支付密钥key放在最后参与签名，组成规则如下：
            参数名1=参数值1&参数名2=参数值2&……&参数名n=参数值n&key=key值
    */

    /**
    The definition of signature rule is as follows : 
    （1） In the list of parameters, except the two parameters of sign_type and sign, all the other parameters that are not in blank shall be signed, the parameter with value as blank doesn’t need to be signed; 
    （2） The sequence of signature shall be in the sequence of parameter name from a to z, in case of same first letter, then in accordance with the second letter, so on so forth, meanwhile, the merchant payment key shall be put at last for signature, and the composition rule is as follows : 
        Parameter name 1 = parameter value 1& parameter name 2 = parameter value 2& ......& parameter name N = parameter value N & key = key value
    */
    
    $signStr= "";
    
    if($bank_code != ""){
        $signStr = $signStr."bank_code=".$bank_code."&";
    }
    if($client_ip != ""){
        $signStr = $signStr."client_ip=".$client_ip."&";
    }
    if($extend_param != ""){
        $signStr = $signStr."extend_param=".$extend_param."&";
    }
    if($extra_return_param != ""){
        $signStr = $signStr."extra_return_param=".$extra_return_param."&";
    }
    
    $signStr = $signStr."input_charset=".$input_charset."&";    
    $signStr = $signStr."interface_version=".$interface_version."&";    
    $signStr = $signStr."merchant_code=".$merchant_code."&";    
    $signStr = $signStr."notify_url=".$notify_url."&";      
    $signStr = $signStr."order_amount=".$order_amount."&";      
    $signStr = $signStr."order_no=".$order_no."&";      
    $signStr = $signStr."order_time=".$order_time."&";  

    if($pay_type != ""){
        $signStr = $signStr."pay_type=".$pay_type."&";
    }

    if($product_code != ""){
        $signStr = $signStr."product_code=".$product_code."&";
    }   
    if($product_desc != ""){
        $signStr = $signStr."product_desc=".$product_desc."&";
    }
    
    $signStr = $signStr."product_name=".$product_name."&";

    if($product_num != ""){
        $signStr = $signStr."product_num=".$product_num."&";
    }   
    if($redo_flag != ""){
        $signStr = $signStr."redo_flag=".$redo_flag."&";
    }
    if($return_url != ""){
        $signStr = $signStr."return_url=".$return_url."&";
    }   

    if($show_url != ""){
        
        $signStr = $signStr."service_type=".$service_type."&";
        $signStr = $signStr."show_url=".$show_url;
    }else{
        
        $signStr = $signStr."service_type=".$service_type;
    }
    
    openssl_sign($signStr,$sign_info,$priKey,OPENSSL_ALGO_MD5);
    
    $sign = base64_encode($sign_info);
    //$html= "<html>";
    //$html .= "<head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'></head>";
    //$html .= "";
echo <<<H
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head> 
    <body onLoad="document.dinpayForm.submit();">
        <form name="dinpayForm" method="post" action="https://pay.dinpay.com/gateway?input_charset=UTF-8" target="_self">
    <input type="hidden" name="sign"          value="{$sign}" />
            <input type="hidden" name="merchant_code" value="{$merchant_code}" />
            <input type="hidden" name="bank_code"     value="{$bank_code}"/>
            <input type="hidden" name="order_no"      value="{$order_no}"/>
            <input type="hidden" name="order_amount"  value="{$order_amount}"/>
            <input type="hidden" name="service_type"  value="{$service_type}"/>
            <input type="hidden" name="input_charset" value="{$input_charset}"/>
            <input type="hidden" name="notify_url"    value="{$notify_url}">
            <input type="hidden" name="interface_version" value="{$interface_version}"/>
            <input type="hidden" name="sign_type"     value="{$sign_type}"/>
            <input type="hidden" name="order_time"    value="{$order_time}"/>
            <input type="hidden" name="product_name"  value="{$product_name}"/>
            <input Type="hidden" Name="client_ip"     value="{$client_ip}"/>
            <input Type="hidden" Name="extend_param"  value="{$extend_param}"/>
            <input Type="hidden" Name="extra_return_param" value="{$extra_return_param}"/>
            <input Type="hidden" Name="pay_type"  value="{$pay_type}"/>
            <input Type="hidden" Name="product_code"  value="{$product_code}"/>
            <input Type="hidden" Name="product_desc"  value="{$product_desc}"/>
            <input Type="hidden" Name="product_num"   value="{$product_num}"/>
            <input Type="hidden" Name="return_url"    value="{$return_url}"/>
            <input Type="hidden" Name="show_url"      value="{$show_url}"/>
            <input Type="hidden" Name="redo_flag"     value="{$redo_flag}"/>
        </form>
    </body>
</html>;
H;
        //echo $html;
    }


    public function zfnotify(Request $request){
        //echo 111;exit;
        $file = './test.txt';
        file_put_contents($file, $_POST["merchant_code"].'-11');
        require_once('merchant.php');
        $pubKey = openssl_get_publickey($pubKey);
        $merchant_code  = $_POST["merchant_code"];  
        $notify_type = $_POST["notify_type"];
        $notify_id = $_POST["notify_id"];
        $interface_version = $_POST["interface_version"];
        $sign_type = $_POST["sign_type"];
        $dinpaySign = base64_decode($_POST["sign"]);
        $order_no = $_POST["order_no"];
        $order_time = $_POST["order_time"]; 
        $order_amount = $_POST["order_amount"];
        $extra_return_param = $_POST["extra_return_param"];
        $trade_no = $_POST["trade_no"];
        $trade_time = $_POST["trade_time"];
        $trade_status = $_POST["trade_status"];
        $bank_seq_no = $_POST["bank_seq_no"];
        $signStr = "";
        if($bank_seq_no != ""){
            $signStr = $signStr."bank_seq_no=".$bank_seq_no."&";
        }

        if($extra_return_param != ""){
            $signStr = $signStr."extra_return_param=".$extra_return_param."&";
        }   
        $signStr = $signStr."interface_version=".$interface_version."&";    
        $signStr = $signStr."merchant_code=".$merchant_code."&";
        $signStr = $signStr."notify_id=".$notify_id."&";
        $signStr = $signStr."notify_type=".$notify_type."&";
        $signStr = $signStr."order_amount=".$order_amount."&";  
        $signStr = $signStr."order_no=".$order_no."&";  
        $signStr = $signStr."order_time=".$order_time."&";  
        $signStr = $signStr."trade_no=".$trade_no."&";  
        $signStr = $signStr."trade_status=".$trade_status."&";  
        $signStr = $signStr."trade_time=".$trade_time;       
        if(openssl_verify($signStr,$dinpaySign,$pubKey,OPENSSL_ALGO_MD5)){          
            
            $out_trade_no = $order_no;

            $recharge = DB::table('recharges')
                ->where('out_trade_no', '=', $out_trade_no)
                ->where('status','=',0)->first;

            if(!$recharge){
                return;
            }    

            $set = array();
            $set['transaction_id'] = $notify_id;
            $set['status'] = 1;
            $set['pay_time'] = $trade_time;
            $where = array();
           
            $res = DB::table('recharges')->where('id','=',$recharge->id)->update($set);
            if(!$res){
                return false;
            }
            $money = $order_amount/100;
            $user = $this->user->find($recharge->user_id);
            //modify_account($openid,$order_amount,1,'充值');
            
            echo "SUCCESS"; 
            
            exit;
            
        }else{
            echo "Signature verification failed";  
           
        }
    }

}